import { ResultUtil } from '../common/HandlerRespUtil';
import { PayloadUtil } from '../common/PayloadUtil';
import { Config } from '../sdk/ConfigManager';
import { LingmaSDKTool } from '../sdk/LingmaSDKTool';
import { ActionEnum, HandlePolicy, RawRequest, RequestPreHandler } from '../sdk/RequestHandleSDK';

/**
 * 自定义脚本过滤器,通过该脚本可以完成将请求内容发送到远程服务器进行处理（如代码扫描、内容审计等）
 */
export const sensitiveContentFilter: RequestPreHandler = {
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
  handle: async (request: RawRequest, SDKTool: LingmaSDKTool) => {
    const dataMap = PayloadUtil.getPayloadData(request.payload);
    // eslint-disable-next-line @typescript-eslint/no-unused-vars
    for (const [key, value] of dataMap.entries()) {
      if (value.includes('password')) {
        return ResultUtil.buildPreHandlerResponse(HandlePolicy.BLOCK, request.payload, '内容包换password');
      }
    }
    // 如果需要针对不同的action做差异化处理，则参考如下实现
    switch (request.action) {
      case ActionEnum.COMPLETION:
        // do something
        break;
      case ActionEnum.CODE_PROBLEM_SOLVE:
        // do something
        break;
      default:
        return ResultUtil.buildPreHandlerResponse(HandlePolicy.NO_OPS, request.payload, '无需处理');
    }
    return ResultUtil.buildPreHandlerResponse(HandlePolicy.NO_OPS, request.payload, '无需处理');
  },
};

/**
 * 将自定义脚本过滤器添加到配置中
 * @param config LingmaExtensionSDK提供的统一管理配置的对象
 */
export function modifyConfig(config: Config) {
  config.contentHandlers.push(sensitiveContentFilter);
  return config;
}
